#include "Utils.h"
#include "RenameThis.h"
#include "XLand.h"
#include <ll/api/plugin/NativePlugin.h>

// 全局变量
ll::Logger logger("XLand");
ll::i18n::SingleFileI18N i18n;
Config config;

namespace rename_this {

RenameThis::RenameThis() = default;

RenameThis& RenameThis::getInstance() {
    static RenameThis instance;
    return instance;
}

ll::plugin::NativePlugin& RenameThis::getSelf() const { return *mSelf; }

bool RenameThis::load(ll::plugin::NativePlugin& self) {
    mSelf = std::addressof(self);
    logger.info("正在初始化插件...");
    auto configFilePath = self.getConfigDir() / "config.json";
    if (!ll::config::loadConfig(config, configFilePath)) {
        logger.warn("Cannot load configurations from {}", configFilePath);
        logger.info("Saving default configurations");
        if (!ll::config::saveConfig(config, configFilePath)) logger.error("Cannot save default configurations to {}", configFilePath);
    }
    i18n = ll::i18n::SingleFileI18N(self.getConfigDir() / "lang.json");
    
    logger.info("初始化数据库"); XLand::initDB();             //初始化数据库
    logger.info("开始构建领地索引"); XLand::buildLand();      //初始化领地数据
    return true;
}

bool RenameThis::enable() {
    getSelf().getLogger().info("Enabling...");
    XUtils::regEvent();      //注册事件
    XUtils::regXLandCmd();   //注册指令
    XUtils::newTaskAll();    //全局计划任务
    Utils::webServer();      //API服务器
    return true;
}

bool RenameThis::disable() {
    getSelf().getLogger().info("disabling...");
    XUtils::removeEvent();   // 卸载事件 
    return true;
}

extern "C" {
    _declspec(dllexport) bool ll_plugin_load(ll::plugin::NativePlugin& self) { return RenameThis::getInstance().load(self);}
    _declspec(dllexport) bool ll_plugin_enable(ll::plugin::NativePlugin&)    { return RenameThis::getInstance().enable();     }
    _declspec(dllexport) bool ll_plugin_disable(ll::plugin::NativePlugin&)   { return RenameThis::getInstance().disable();    }
    /// @warning Unloading the plugin may cause a crash if the plugin has not released all of its
    /// resources. If you are unsure, keep this function commented out.
    // _declspec(dllexport) bool ll_plugin_unload(ll::plugin::NativePlugin&) {
    //     return RenameThis::getInstance().unload();
    // }
}
} // namespace rename_this
